﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.IO;
using FileMonitor.Configuration.Prototype;
namespace FileMonitor.Service.Provider.FileMonitor.Utility
{
    public class FileUtil
    {
        #region Utility Methods
        public bool IsMonitorFile(string fileName, FileProcessConfiguration allConfig)
        {
            bool isMonitorFileType = IsMonitorFileType(fileName, allConfig);
            bool isMonitorPlantCode = IsMonitorPlantCode(fileName, allConfig);
            return (isMonitorFileType && isMonitorPlantCode);
        }

        public bool IsIgnoredFile(string fileName, FileProcessConfiguration allConfig)
        {
            bool isMonitorFileType = IsMonitorFileType(fileName, allConfig);
            bool isMonitorPlantCode = IsMonitorPlantCode(fileName, allConfig);
            return (!isMonitorPlantCode) && isMonitorFileType;
        }

        public bool IsMonitorFileType(string fileName, FileProcessConfiguration allConfig)
        {
            string extName = "*" + fileName.Substring(fileName.LastIndexOf("."));
            string configFilters = allConfig.Filter;
            string[] filterArr = configFilters.Split(",".ToCharArray());
            for (int i = 0; i < filterArr.Length; i++)
            {
                filterArr[i] = filterArr[i].ToUpper();
            }
            if (filterArr.Contains("*.*"))
                return true;
            return filterArr.Contains(extName.ToUpper());
        }

        public bool IsMonitorPlantCode(string FileName, FileProcessConfiguration allConfig)
        {
            string configFilterPlantCodes = allConfig.FilterPlantCode;
            FileName = FileName.Substring(FileName.LastIndexOf("\\") + 1);
            string plantCode = GetPlantCodeFromFileName(FileName, allConfig);
            if (string.IsNullOrEmpty(configFilterPlantCodes))
            {
                return true;
            }
            else
            {
                string[] filterPlants = configFilterPlantCodes.Split(",".ToCharArray());
                return (!filterPlants.Contains(plantCode));
            }

        }

        public void EnsureCreateSubFolder(string monitorPath, string subFolderName)
        {
            monitorPath = monitorPath + "\\" + subFolderName;
            if (!System.IO.Directory.Exists(monitorPath))
            {
                System.IO.Directory.CreateDirectory(monitorPath);
            }
        }

        public void MovePeocessFile(string fileName, string path, FileProcessConfiguration allConfig)
        {

            if (IsUnZipFile(fileName))
            {
                UnZipFileToSubFolder(fileName, path, "temp");
                System.Threading.Thread.Sleep(1000);
                MoveFileToSubFolder(fileName, path, "temp");
            }
            else
            {
                string configFilters = allConfig.Filter;
                string configFilterPlantCodes = allConfig.FilterPlantCode;
                if (IsMonitorFile(fileName, allConfig))
                {
                    MoveFileToSubFolder(fileName, path, "temp");
                }
                else if (IsIgnoredFile(fileName, allConfig))
                {
                    MoveFileToSubFolder(fileName, path, "ignored");
                }
            }
        }
 
        public List<string> MovePeocessFileReturnTarget(string fileName, string path, FileProcessConfiguration allConfig)
        {
            try
            {
                List<string> targetFiles = new List<string>();
                if (IsUnZipFile(fileName))
                {
                    string tempFolderName = GenrateTempFolderForUnZip(fileName, path);
                    UnZipFileToSubFolder(fileName, path, tempFolderName);
                    string tempPath = path + "\\" + tempFolderName;
                    string[] zipFiles = System.IO.Directory.GetFiles(tempPath);
                    foreach (string fileFullPath in zipFiles)
                    {
                        MoveFileToSubFolder(fileFullPath, path, "temp");
                        string actualFileName = fileFullPath.Substring(fileFullPath.LastIndexOf("\\") + 1);
                        string targetFileName = string.Format("{0}\\{1}\\{2}", path, "temp", actualFileName);
                        targetFiles.Add(targetFileName);
                    }
                    System.Threading.Thread.Sleep(1000);
                    MoveFileToSubFolder(fileName, path, "ignored");
                }
                else
                {
                    if (IsMonitorFile(fileName, allConfig))
                    {
                        MoveFileToSubFolder(fileName, path, "temp");
                        string actualFileName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
                        string currentPath = string.Format("{0}\\{1}\\{2}", path, "temp", actualFileName);
                        targetFiles.Add(currentPath);
                    }
                    else if (IsIgnoredFile(fileName, allConfig))
                    {
                        MoveFileToSubFolder(fileName, path, "ignored");
                    }
                }
                return targetFiles;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private string GenrateTempFolderForUnZip(string zipfileName, string parentPath)
        {
            string fileName = zipfileName.Substring(zipfileName.LastIndexOf("\\") + 1);
            string folderName = fileName + "_" + System.DateTime.Now.ToString("yyyyMMdd");
            string tempPath = parentPath + "\\" + folderName;
            if (System.IO.Directory.Exists(tempPath))
            {
                System.IO.Directory.Delete(tempPath);
            }
            System.IO.Directory.CreateDirectory(tempPath);
            return folderName;
          
        }

        private void MoveFileToSubFolder(string fileFullPath, string ParentPath, string subPath)
        {
            string fileName = fileFullPath.Substring(fileFullPath.LastIndexOf("\\") + 1);
            System.IO.File.Move(fileFullPath, ParentPath + "\\" + subPath + "\\" + fileName);
        }

        private void UnZipFileToSubFolder(string fileFullPath, string ParentPath, string subPath)
        {
            FileUtility.ZIP.UnZip unZip = new FileUtility.ZIP.UnZip();
            unZip.UnZipFile(fileFullPath, ParentPath + "\\" + subPath + "\\", true);
        }

        public  FileSystemEventArgs InitializeFileEventArgs(string fileFullPath,WatcherChangeTypes changeType)
        {

            string fileName = Path.GetFileName(fileFullPath);//fileFullPath.Substring(fileFullPath.LastIndexOf("\\") + 1);
            string directory = Path.GetDirectoryName(fileFullPath);//fileFullPath.Substring(0,fileFullPath.LastIndexOf("\\"));
            FileSystemEventArgs args = new FileSystemEventArgs(changeType, directory, fileName);
            return args;
        }
        
        public bool IsUnZipFile(string fileName)
        {
            return fileName.EndsWith(".zip", true, null) || fileName.EndsWith(".rar", true, null) || fileName.EndsWith(".7z", true, null);
        }


        public void EnsureMoveTempFolderFiles(string tempFoler, string monitorFolder)
        {
            string[] files = System.IO.Directory.GetFiles(tempFoler);
            foreach (string fileFullPath in files)
            {
                string fileName = fileFullPath.Substring(fileFullPath.LastIndexOf("\\") + 1);
                System.IO.File.Move(fileFullPath, monitorFolder + "\\" + fileName);
            }
        }

        public string GetPlantCodeFromFileName(string FileName, FileProcessConfiguration allConfig)
        {
            string plantCodeIndex = string.IsNullOrEmpty(allConfig.PlantCodeIndex) ? "0" : allConfig.PlantCodeIndex;
            string plantCodeLength = string.IsNullOrEmpty(allConfig.PlantCodeLength) ? "4" : allConfig.PlantCodeLength;
            string plantCode = FileName.Substring(Int32.Parse(plantCodeIndex), Int32.Parse(plantCodeLength));
            return plantCode;
        }


        #endregion
    }
}
